#include "hal_adc.h"
#include "stm32f0xx_adc.h"

#define VOL_1000 3300 
#define ADC_MAX  2047

void hal_adc_int(void)
{
  ADC_InitTypeDef     ADC_InitStructure;
  GPIO_InitTypeDef    GPIO_InitStructure;
  
  
  /* ADC1 Periph clock enable */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
  
  /* Configure ADC Channel11 as analog input */

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 ;

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
  
  /* ADCs DeInit */  
  ADC_DeInit(ADC1);
  
  /* Initialize ADC structure */
  ADC_StructInit(&ADC_InitStructure);
  
  /* Configure the ADC1 in continuous mode with a resolution equal to 12 bits  */
  ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
  ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; 
  ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
  ADC_Init(ADC1, &ADC_InitStructure); 
  
  /* Convert the ADC1 Channel 11 with 239.5 Cycles as sampling time */ 

  ADC_ChannelConfig(ADC1, ADC_Channel_1 , ADC_SampleTime_239_5Cycles);


  /* ADC Calibration */
  ADC_GetCalibrationFactor(ADC1);
  
  /* Enable the ADC peripheral */
  ADC_Cmd(ADC1, ENABLE);     
  
  /* Wait the ADRDY flag */
  while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADRDY)); 
  
  /* ADC1 regular Software Start Conv */ 
  ADC_StartOfConversion(ADC1);
}

uint16 hal_adc_get_vol(uint8 pin)
{
  uint32 adc = 0;
  uint32_t tempVal,i;

    tempVal = ADC_GetConversionValue(ADC1);

    while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);

    /* Get ADC1 converted data */
    tempVal = ADC_GetConversionValue(ADC1);

    tempVal = 0x00;

    for(i = 0; i < 4; i++)
    {
        while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);

        /* Get ADC1 converted data */
        tempVal += ADC_GetConversionValue(ADC1);
    }

    tempVal >>= 2;  
    
    //os_log("ad is %d", tempVal);
    
    if(tempVal > 0 && tempVal <= 1360)
    {
        adc = 1;
    }
    else if(tempVal > 1360 && tempVal <= 1470)
    {
        adc = 22;
    }
    else
    {
        adc = 100;
    }
	
  return adc;
}
